package model;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;


import javax.servlet.http.HttpSession;


import myutil.Connect;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class ImageUploadMo{
	Connect c;
	ResultSet rs;
		public void insertpicture(File attached_file, String file_name) 
		{
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			String uploader_email_id = session.getAttribute("username")
					.toString();
			if (attached_file != null) 
			{
				c = new Connect();
				// int uploader_id=0;
				
				String query="select picture_name from profile_picture where user_id='"+uploader_email_id+"'";
				System.out.println(query);
				int count=0;
				String previous_file ="";
				try {
					ResultSet rs=c.getResult(query);
					while(rs.next()){
						count=count+1;
						previous_file=rs.getString("picture_name");
					}
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			if (count==0){
				try {
					c.dml("insert into profile_picture(user_id,picture_name) values('"
							+ uploader_email_id + "','" + file_name + "')");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
				// System.out.println(getServlet().getServletContext().getRealPath(""));
				File f = new File(
						"F:/Metalink/attachments/"
								+ uploader_email_id);
				
				f.mkdir();
			
				File f1 = new File(
						"F:/Metalink/attachments/"
								+ uploader_email_id + "/" + file_name);
				try {
					FileUtils.copyFile(attached_file, f1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else{
				File f2=new File("F:/Metalink/attachments/"+uploader_email_id+"/"+previous_file);
				boolean s=f2.delete();
				System.out.println("deleted file is:"+s);
				try {
					c.dml("update profile_picture set picture_name='" + file_name + "' where user_id='"+uploader_email_id+"'");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				File f1 = new File(
						"F:/Metalink/attachments/"
								+ uploader_email_id + "/" + file_name);
				try {
					FileUtils.copyFile(attached_file, f1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			}
		}
}